package com.atwisdom.star.core.bsl.business.Impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.atwisdom.star.common.util.DateUtils;
import com.atwisdom.star.common.vo.JsonResult;
import com.atwisdom.star.common.vo.ModelType;
import com.atwisdom.star.common.vo.ResultInfo;
import com.atwisdom.star.common.vo.StatusCode;
import com.atwisdom.star.core.bsl.business.WorkReportBslService;
import com.atwisdom.star.core.bsl.business.utils.ConstantInfo;
import com.atwisdom.star.core.dao.pojo.modelClass.hier.HierInstance;
import com.atwisdom.star.core.dsl.functionClass.Impl.BatchNumberDslServiceImpl;
import com.atwisdom.star.core.dsl.modelClass.hier.Impl.HierInstanceDslServiceImpl;
import com.atwisdom.star.core.dsl.modelClass.logic.Impl.LogicInstanceDslServiceImpl;
import com.atwisdom.star.exception.pojo.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class WorkReportBslServiceImpl implements WorkReportBslService {
    private LogicInstanceDslServiceImpl logicInstanceDslService;

    private HierInstanceDslServiceImpl hierInstanceDslService;

    private BatchNumberDslServiceImpl batchNumberDslService;

    @Autowired
    public void setHierInstanceDslService(HierInstanceDslServiceImpl hierInstanceDslService) {
        this.hierInstanceDslService = hierInstanceDslService;
    }

    @Autowired
    public void setLogicInstanceDslService(LogicInstanceDslServiceImpl logicInstanceDslService) {
        this.logicInstanceDslService = logicInstanceDslService;
    }

    @Autowired
    public void setBatchNumberDslService(BatchNumberDslServiceImpl batchNumberDslService) {
        this.batchNumberDslService = batchNumberDslService;
    }

    /**
     * 报工暂停与开启
     * @param stopStatusData 参数
     * @return 返回结果
     */
    @Transactional
    @Override
    public ResultInfo<?> dealWorkReportStopStatus(JSONObject stopStatusData) {
        String stopStatus = stopStatusData.getString("stopStatus");
        Long instanceId = stopStatusData.getLong("instanceId");
        String stopDescription = stopStatusData.getString("stopDescription");
        String stopParentId = "4bljvfa95wk000";
        String parentId = "4ja1eoa9f6o000";
        String className ="workReport";
        String workReportEndTime = "workReportEndTime";
        List<HierInstance> workReportHierInstances = this.hierInstanceDslService.fetchByParentId(ModelType.Logic.getCode(),className, instanceId, parentId);
        List<HierInstance> hierInstances = workReportHierInstances.stream().filter(wr -> wr.getValues().getDate(workReportEndTime) == null).collect(Collectors.toList());
        if(CollectionUtil.isEmpty(hierInstances)){
            return JsonResult.error(StatusCode.ERROR_UPDATE.getCode(),"没有要更新的数据");
        }

        List<Long> idList = hierInstances.stream().map(HierInstance::getId).collect(Collectors.toList());
        JSONObject hierData = new JSONObject();
        hierData.put("ids",idList);
        JSONObject hierValues = new JSONObject();

        JSONObject data = new JSONObject();
        data.put("id",instanceId);
        JSONObject values = new JSONObject();
        values.put("stopStatus",stopStatus);
        data.put("values",values);
        logicInstanceDslService.updateById(data);

        if(stopStatus.equalsIgnoreCase(ConstantInfo.STOP_STATUS)){
            String workReportStopTime = DateUtils.getLocalDateTimeFormat(new Date(), "yyyy-MM-dd HH:mm:ss");
            this.saveWorkReportStop(stopParentId, instanceId, className, workReportStopTime, stopDescription, idList);
            hierValues.put("workReportStopTime", workReportStopTime);
        }else{
            Date workReportStopTime = hierInstances.get(0).getValues().getDate("workReportStopTime");
            Date workReportOpenTime = new Date();
            Double workReportStopDuration = hierInstances.get(0).getValues().getDouble("workReportStopDuration");
            if(workReportStopDuration==null){
                workReportStopDuration = 0.0;
            }
            Double hoursBetween = DateUtils.getHoursBetween(workReportStopTime, workReportStopTime);
            workReportStopDuration +=hoursBetween;
            hierValues.put("workReportOpenTime", DateUtils.getLocalDateTimeFormat(workReportOpenTime, "yyyy-MM-dd HH:mm:ss"));
            hierValues.put("workReportStopDuration",workReportStopDuration);
        }
        hierData.put("values",hierValues);
        this.hierInstanceDslService.updateByIds(hierData);
        return JsonResult.success(StatusCode.SUCCESS);
    }


    /**
     * 异常完工，生成设备或模具维修申请
     * @param repairData 维修设备参数
     * @return 返回成功或失败
     */
    @Transactional
    @Override
    public ResultInfo<?> dealAbnormalFinishRepair(JSONObject repairData) {
        try {
            System.out.println("******************异常报工维修参数：" + repairData);
            JSONObject repairParam = repairData.getJSONObject("repairParam");
            JSONArray equipIds = repairParam.getJSONArray("equipIds");
            String repairReason = repairParam.getString("repairReason");
            String applyPerson = repairParam.getString("applyPerson");
            Long workReportId = repairParam.getLong("workReportId");
            String workReportNumber = repairParam.getString("workReportNumber");
            String workOrderNumber = repairParam.getString("workOrderNumber");
            String applyTime = DateUtils.getLocalDateTimeFormat(new Date(), "yyyy-MM-dd HH:mm:ss");
            int year = LocalDate.now().getYear();
            if (CollectionUtil.isNotEmpty(equipIds)) {
                List<Long> equipIdList = JSONUtil.parseArray(equipIds).toList(Long.class);
                String code = String.format("EquipRApply-%s", year);
                genRepairAppLy(equipIdList,repairReason, applyPerson, code, workReportId, workReportNumber, workOrderNumber,applyTime, "EquipRepairApply");
            }

            JSONArray mouldIds = repairParam.getJSONArray("mouldIds");
            if (CollectionUtil.isNotEmpty(mouldIds)) {
                List<Long> mouldIdList = JSONUtil.parseArray(mouldIds).toList(Long.class);
                String code = String.format("MouldRepairApply-%s", year);
                genRepairAppLy(mouldIdList,repairReason,applyPerson, code, workReportId, workReportNumber, workOrderNumber,applyTime, "MouldRepairApply");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new BusinessException("999999", "生成维修申请数据报错", ex);
        }

        return JsonResult.success(StatusCode.SUCCESS);
    }

    /**
     * 生成设备或模具申请单
     * @param equipIdList 设备Id列表
     * @param repairReason 维修原因
     * @param applyPerson 申请人
     * @param code 生成自动编码code
     * @param workReportId 报工单Id
     * @param workReportNumber 报工单编号
     * @param applyTime 申请时间
     * @param className 生成申请所属的类
     */
    private void genRepairAppLy(List<Long> equipIdList,String repairReason, String applyPerson, String code, Long workReportId, String workReportNumber, String workOrderNumber,String applyTime,String className) {
        List<JSONObject> jsonDataList = new ArrayList<>();
        for (Long equipId : equipIdList) {
            JSONObject data = new JSONObject();
            data.put("className",className);
            data.put("type","logic");
            JSONObject values = new JSONObject();
            values.put("equipId",equipId);
            values.put("repairReason", repairReason);
            values.put("applyPerson", applyPerson);
            values.put("repairType","0");
            values.put("code",batchNumberDslService.getNextVal(code));
            values.put("sourceId", workReportId);
            values.put("sourceCode", workReportNumber);
            values.put("workOrderNumber", workOrderNumber);
            values.put("applyTime", applyTime);
            values.put("status","0");
            data.put("values",values);
            jsonDataList.add(data);
        }
        this.logicInstanceDslService.batchAdd(jsonDataList);
    }

    /**
     * 报工暂停维护
     * @param stopParentId 暂停父节点Id
     * @param instanceId 工单实例Id
     * @param className 工单类名
     * @param workReportStopTime 暂停时间
     * @param stopDescription 暂停描述
     * @param idList 报工明细Id
     */
    private void saveWorkReportStop(String stopParentId, Long instanceId, String className, String workReportStopTime, String stopDescription, List<Long> idList) {
        JSONObject hierInstanceJson = new JSONObject();
        hierInstanceJson.put("parentId", stopParentId);
        hierInstanceJson.put("containerId", instanceId);
        hierInstanceJson.put("containerModel", ModelType.Logic.getCode());
        hierInstanceJson.put("className", className);
        JSONObject stopValues = new JSONObject();
        stopValues.put("workReportStopTime", workReportStopTime);
        stopValues.put("stopDescription", stopDescription);
        stopValues.put("workReportIds", idList);
        hierInstanceJson.put("values", stopValues);
        this.hierInstanceDslService.addChild(hierInstanceJson);
    }
}
